// src/stores/loginUserStore.ts
import {ref, watch} from 'vue';
import { defineStore } from 'pinia';
import ACCESS_ENUM from '@/access/accessEnum';
import { UserControllerService } from '../../openapi';

export const useLoginUserStore = defineStore("loginUser", () => {
  const loginUser = ref<any>({
    userAccount: "未登录",
    userRole: ACCESS_ENUM.NOT_LOGIN,
  });

  // 从 localStorage 恢复状态
  const restoreState = () => {
    const savedState = localStorage.getItem('loginUser');
    if (savedState) {
      loginUser.value = JSON.parse(savedState);
    }
  };

  // 保存状态到 localStorage
  const saveState = () => {
    localStorage.setItem('loginUser', JSON.stringify(loginUser.value));
  };

  // 清除状态,退出的时候调用
  const clearState = () => {
    loginUser.value = {
      userAccount: "未登录",
      userRole: ACCESS_ENUM.NOT_LOGIN,
    };
    localStorage.removeItem('loginUser');
  };

  // 监听状态变化并保存
  watch(
    () => loginUser.value,
    () => saveState(),
    { deep: true }
  );

  async function getLoginUser() {
    const res = await UserControllerService.getCurrentUserUsingGet();
    console.log("res", res);
    if (res.code === 200 && res.data) {
      loginUser.value = res.data;
      // } else {
      //   setTimeout((): void => {
      //     loginUser.value = {
      //       username: "小黑子",
      //       id: 1,
      //     };
      //   }, 3000);
    }
  }

  function setLoginUser(newLoginUser: any) {
    loginUser.value = newLoginUser;
  }

  return { loginUser, setLoginUser, getLoginUser, restoreState, clearState};
});
